package com.krain.ddbb.activity;


import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.krain.corelibrary.helper.imageloader.ImageLoader;
import com.krain.corelibrary.widget.CircleImageView;
import com.krain.ddbb.R;
import com.krain.ddbb.base.BaseActivity;
import com.krain.ddbb.constant.Constant;
import com.krain.ddbb.entity.AppApi;
import com.krain.ddbb.entity.PersonDetailBean;
import com.krain.ddbb.entity.UpLoadBean;
import com.krain.ddbb.entity.UserCardBean;
import com.krain.ddbb.entity.UserInfoBean;
import com.krain.ddbb.entity.WorkNameBean;
import com.krain.ddbb.util.crop.Crop;
import com.krain.ddbb.util.crop.CropImageHelper;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;



@EActivity(R.layout.activity_user_info)
public class UserInfoActivity extends BaseActivity {

    @ViewById(R.id.act_userinfo_civ_head)
    CircleImageView mCrcHead;//用户头像
    @ViewById(R.id.act_userinfo_et_name)
    EditText mEtName;//输入用户名
    @ViewById(R.id.act_userinfo_et_phone)
    EditText mEtPhone;//输入手机号
    @ViewById(R.id.act_login_rl_craft)
    RelativeLayout mRlCraft;//RL工种

    @ViewById(R.id.act_login_tv_craft_type)
    TextView mTvCraft;//工种
    @ViewById(R.id.tv_craft_arrow)
    TextView mTvCraft_Arrow;//工种箭头
    @ViewById(R.id.act_login_rl_location)
    RelativeLayout mRlLocation;//RL常用住址

    @ViewById(R.id.act_login_tv_location_type)
    TextView mTvLocation;//常用住址
    @ViewById(R.id.tv_location_arrow)
    TextView mTvLocation_Arrow;//常用住址箭头
    @ViewById(R.id.act_login_iv_add_card)
    ImageView mImvAdd_Card;//添加身份证按钮
    @ViewById(R.id.act_login_iv_id_card)
    ImageView mImvCard;//身份证
    int picType;
    private final int TYPE_ID = 1;
    private final int TYPE_AVATAR = 2;


    private boolean isoncl = true;
    private ArrayList<WorkNameBean> work = new ArrayList<WorkNameBean>();
    private UserInfoBean mUserInfoBean;
    private static final int CAMERAL_REQUEST_CODE = 2;
    private static final int ALUBUM_REQUEST_CODE = 1;
    public String filePath = null;
    private static final String TEMP_AVATAR_NAME = "temp";
    private String headPicUrl = null;
    private String imgName = null;
    File temp = null;
    String url;
    private String avatarUrl = "";
    private String idUrl = "";


    /**
     * 选择修改头像的方式对话框
     */
    private void showIdDialog() {
        picType = TYPE_ID;
        showDialog(this, getString(R.string.user_id_card), getString(R.string.choose_change_avatar_means), getString(R.string.album), getString(R.string.take_photo), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, ALUBUM_REQUEST_CODE);
                closeDialog();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 调用快速拍照功能，查看you_sdk_path/docs/guide/topics/media/camera.html
                 */
                if (filePath != null) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 下面这句指定调用相机拍照后的照片存储的
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath, TEMP_AVATAR_NAME)));
                    startActivityForResult(intent, CAMERAL_REQUEST_CODE);
                } else {
                    baseUtil.showSnackBar(UserInfoActivity.this, "当前无SD卡,无法使用拍照");
                }
                closeDialog();
            }
        }, true);

    }


    @Click(R.id.act_login_iv_add_card)
    void addIdCard() {
        showIdDialog();
    }


    @AfterViews
    void afterView() {
        try {
            filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
        } catch (Exception e) {
            filePath = null;
        }
        initUserInfo();
        mTvCraft_Arrow.setVisibility(View.GONE);
        mTvLocation_Arrow.setVisibility(View.GONE);
        mImvAdd_Card.setVisibility(View.GONE);
        mImvCard.setVisibility(View.VISIBLE);
        mRlCraft.setEnabled(false);
        mRlLocation.setEnabled(false);
        mEtName.setEnabled(false);
        mEtPhone.setEnabled(false);
        mCrcHead.setEnabled(false);
    }

    @Background
    void initUserInfo() {
        getUserInfo();
    }

    @UiThread
    void setView(UserInfoBean mPerson) {
        if (mPerson == null) {
            return;
        }
        final PersonDetailBean mPersonDetailBean = mPerson.getDetail();
        UserCardBean cardBean = mPerson.getUserCard();
        if (mPersonDetailBean == null) {
            return;
        } else {
            mEtName.setText(mPersonDetailBean.getUsername());
            mEtPhone.setText(mPersonDetailBean.getPhone());
            if (!TextUtils.isEmpty(mPersonDetailBean.getPicture())) {
                ImageLoader.getInstance(this).loadImage(this, mCrcHead, mPersonDetailBean.getPicture(), R.mipmap.head_icon);
            } else {
                mCrcHead.setImageDrawable(getResources().getDrawable(R.mipmap.head_icon));
            }
            UserInfoBean info = app.getmUserinfo();
            StringBuffer string = new StringBuffer();
            for (int i = 0; i < info.getWork().size(); i++) {
                string.append(info.getWork().get(i).getWork_name() + "、");
            }
            if (string.length() > 1)
                string.delete(string.length() - 1, string.length());
            mTvCraft.setText(string);
            mTvLocation.setText("       "+info.getAddress().getAddress());
            if (!TextUtils.isEmpty(cardBean.getFront_image())) {
                ImageLoader.getInstance(this).loadImage(this, mImvCard, cardBean.getFront_image());
            }
        }
    }

    /**
     * 得到用户信息
     */
    @Background
    void getUserInfo() {
        UserInfoBean userbean = AppApi.getsInstance(mContext).getUserInfo(app.getmUserinfo().getAccess_token());
        if (userbean != null) {
            app.setmUserinfo(userbean);
            setView(userbean);
        }
    }

    /**
     * 修改个人信息
     */
    @Background
    void setUserInfo() {
        UserInfoBean userbean = AppApi.getsInstance(mContext).setUserInfo(app.getmUserinfo().getAccess_token(), mEtName.getText().toString(), avatarUrl, idUrl, idUrl);
        if (userbean != null) {
            app.setmUserinfo(userbean);
            setView(userbean);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_search) {
            if (isoncl) {
                item.setIcon(R.mipmap.ic_footprintchecked);
                mEtName.setEnabled(true);
                mEtPhone.setEnabled(true);
                mCrcHead.setEnabled(true);
                mTvCraft_Arrow.setVisibility(View.VISIBLE);
                mTvLocation_Arrow.setVisibility(View.VISIBLE);
                mImvAdd_Card.setVisibility(View.VISIBLE);
                mImvCard.setVisibility(View.VISIBLE);
                mRlCraft.setEnabled(true);
                mRlLocation.setEnabled(true);
                isoncl = false;
            } else {
                item.setIcon(R.mipmap.bianji);
                mImvAdd_Card.setVisibility(View.GONE);
                mTvCraft_Arrow.setVisibility(View.GONE);
                mTvLocation_Arrow.setVisibility(View.GONE);
                mImvCard.setVisibility(View.VISIBLE);
                mRlCraft.setEnabled(false);
                mRlLocation.setEnabled(false);
                mEtName.setEnabled(false);
                mEtPhone.setEnabled(false);
                mCrcHead.setEnabled(false);
                isoncl = true;
                setUserInfo();
            }
        }
        return true;
    }

    @Click(R.id.act_login_rl_craft)
    void clickToCraft() {
        UserWorkActivity.jumpTothisActivity(this);
    }

    @Click(R.id.act_login_rl_location)
    void clickToLocation() {
        UserAddresActivity.jumpTothisActivity(this);
    }


    /**
     * 更改用户头像
     */
    @Click(R.id.act_userinfo_civ_head)
    void onClickUserHead() {
        ShowPickDialog();
    }


    /**
     * 选择修改头像的方式对话框
     */
    private void ShowPickDialog() {
        picType = TYPE_AVATAR;
        showDialog(this, getString(R.string.user_head), getString(R.string.choose_change_avatar_means), getString(R.string.album), getString(R.string.take_photo), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, ALUBUM_REQUEST_CODE);
                closeDialog();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 调用快速拍照功能，查看you_sdk_path/docs/guide/topics/media/camera.html
                 */
                if (filePath != null) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 下面这句指定调用相机拍照后的照片存储的路径
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath, TEMP_AVATAR_NAME)));
                    startActivityForResult(intent, CAMERAL_REQUEST_CODE);
                } else {
                    baseUtil.showSnackBar(UserInfoActivity.this, "当前无SD卡,无法使用拍照");
                }
                closeDialog();
            }
        }, true);

    }

    public static void jumpTothisActivity(BaseActivity activity) {
        Intent intent = new Intent(activity, UserInfoActivity_.class);
        activity.startActivity(intent);
    }

    @Override
    protected String getToolbarTitle() {
        return "我的信息";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 如果是直接从相册获取
                case ALUBUM_REQUEST_CODE:
                    if (data != null) {
                        temp = CropImageHelper.getFile(data, this);
                        CropImageHelper.rotateBitmap(temp, this);
                    }
                    break;
                // 如果是调用相机拍照时
                case CAMERAL_REQUEST_CODE:
                    temp = new File(filePath + File.separator + TEMP_AVATAR_NAME);
                    CropImageHelper.rotateBitmap(temp, this);
                    break;
                // 取得裁剪后的图片
                case Crop.REQUEST_CROP:
                    handleCrop(picType, resultCode, data);
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void handleCrop(int picType, int resultCode, Intent result) {
        Uri uri = Crop.getOutput(result);
        try {
            File file = new File(new URI(uri.toString()));
            uploadAvatarToserver(picType, file);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    // 上传头像到服务器
    @Background(id = "uploadFile")
    void uploadAvatarToserver(int picType, File file) {
        UpLoadBean result = AppApi.getsInstance(mContext).postFile(app.getmUserinfo().getAccess_token(), file);
        if (result == null) {
            baseUtil.showSnackBar(mContext, "上传图片出错");
            return;
        }
        String url = new StringBuffer(Constant.HOSTURL).append(result.getImage()).toString();
        if (result != null) {
            if (picType == TYPE_AVATAR)
                setViewData(url);
            else
                setIdView(url);
            Logger.i("result", result);
        }

    }

    /**
     * 设置上传后的头像
     */
    @UiThread
    void setViewData(String url) {
        avatarUrl = url;
        ImageLoader.getInstance(this).loadImage(this, mCrcHead, url, R.mipmap.head_icon);
    }


    @UiThread
    void setIdView(String url) {
        idUrl = url;
        ImageLoader.getInstance(this).loadImage(this, mImvCard, url);

    }

}